//
//  UserRegisterViewController.m
//  YoucApp
//
//  Created by Liam on 11/19/12.
//
//

#import "UserRegisterViewController.h"
#import "UserManager.h"

@interface UserRegisterViewController ()

@end

@implementation UserRegisterViewController

@synthesize textEmail = _textEmail;
@synthesize textPassword = _textPassword;
@synthesize textRePassword = _textRePassword;
@synthesize textNickname = _textNickname;

- (NSNumber *)isValidEmail:(NSString *)checkString
{
	BOOL stricterFilter = YES;
	NSString *stricterFilterString = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
	NSString *laxString = @".+@.+\\.[A-Za-z]{2}[A-Za-z]*";
	NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
	NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
	return [NSNumber numberWithBool:[emailTest evaluateWithObject:checkString]];
}

- (NSNumber *)isValidPassword:(NSString *)password
{
	BOOL bRet = ([password length] >= 6);
	
	return [NSNumber numberWithBool:bRet];
}

- (NSNumber *)isValidNickname:(NSString *)nickname
{
	BOOL bRet = ([nickname length] >= 1);
	
	return [NSNumber numberWithBool:bRet];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
	self.title = @"注册";
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
	[_textEmail release];
	[_textPassword release];
	[_textRePassword release];
	[_textNickname release];
    [super dealloc];
}

- (void)viewDidUnload {
	[self setTextEmail:nil];
	[self setTextPassword:nil];
	[self setTextRePassword:nil];
	[self setTextNickname:nil];
    [super viewDidUnload];
}

- (IBAction)inputDone
{
	NSString * email = self.textEmail.text;
	NSString * password = self.textPassword.text;
	NSString * rePassword = self.textRePassword.text;
	NSString * nickname = self.textNickname.text;
	
	if (![self isValidTextField:self.textEmail checkSelector:@selector(isValidEmail:) errMsg:@"请输入正确的邮箱地址"])
	{
		return;
	}
	
	if (![self isValidTextField:self.textPassword checkSelector:@selector(isValidPassword:) errMsg:@"请输入正确的密码"])
	{
		return;
	}
	
	if ([password compare:rePassword] != NSOrderedSame)
	{
		[self showAlert:@"两次密码不相等"];
		[self.textRePassword becomeFirstResponder];
		return;
	}
	
	if (![self isValidTextField:self.textNickname checkSelector:@selector(isValidNickname:) errMsg:@"请输入正确的昵称"])
	{
		return;
	}
	
	[[UserManager instance] userRegister:email password:password nickname:nickname];
	
	[super inputDone];
}

- (NSString *)getPassword
{
	return self.textPassword.text;
}

@end
